<template>
    <div class="packaging-add">
        <a-modal width="90%" :visible="visible" :title="modalOption.title" @ok="modalOption.onOk" :dialog-style="{ top: '20px' }"
            @cancel="modalOption.onCancel" :okText="modalOption.okText" :cancelText="modalOption.cancelText"
            class="yuan-modal packaging-add-modal">
            <a-spin tip="Loading..." :spinning="formLoading">
                <a-form-model layout="inline" class="yuan-form" ref="form" :model="formData" :rules="rules"
                    :label-col="{ style: { width: '100px' } }" :wrapper-col="{ style: { width: 'calc(100% - 120px)' } }">
                    <div class="form-panel">
                        <div class="form-panel-title">产品信息</div>
                        <div class="form-panel-box yuan-form-col3">
                            <a-form-model-item class="yuan-form-item" label="产品类型">
                                <a-radio-group v-if="visible" disabled :default-value="rawType">
                                    <a-radio v-for="(item,i) in tabsData" :key="item.rawType" :value="item.rawType">{{item.name}}</a-radio>
                                </a-radio-group>
                            </a-form-model-item>
                            <a-form-model-item v-if="formData.productType === '中药饮片'" class="yuan-form-item yuan-form-col3" label="中药等级" prop="medicineClass">
                                <a-radio-group v-model="formData.medicineClass" class="yuan-form-input" @change="medicineClassChange">
                                    <a-radio value="统货">统货</a-radio>
                                    <a-radio value="选货">选货</a-radio>
                                </a-radio-group>
                            </a-form-model-item>
                            <div class="clear-both"></div>
                            <a-form-model-item class="yuan-form-item" label="产品大类" prop="productBigKind">
                                <YuanSelectVue v-if="confirmMedicineClass" show-search class="yuan-form-input" placeholder="请选择" :list="bigKindList"
                                               v-model="formData.productBigKind" @change="productBigKindChange"
                                               :defName="formData.productBigKind" />
                                <span class="yuan-form-placeholder" v-else>请先选择中药等级</span>
                            </a-form-model-item>


                            <a-form-model-item class="yuan-form-item yuan-form-col3" label="包装规格" prop="discretion">
<!--                                <a-select class="yuan-form-input" v-if="formData.productBigKind" v-model="formData.discretion" placeholder="请选择装量" @change="discretionChange">-->
<!--                                    <a-select-option :value="item.value" v-for="(item,idx) in quantityColor" :key="item.name+'_'+idx">{{item.value}}</a-select-option>-->
<!--                                </a-select>-->
                                <a-select @change="packSpecificationChange" class="yuan-form-input" v-if="formData.productBigKind" v-model="formData.discretion" placeholder="请选择包装规格">
                                    <a-select-option v-for="(item,i) in packSpecificationList" :key="i" :value="item">{{item}}</a-select-option>
                                </a-select>
                                <span class="yuan-form-placeholder" v-else>请先选择产品大类</span>
                            </a-form-model-item>

                            <a-form-model-item v-if="formData.productType === '直服饮片'" class="yuan-form-item" label="包装形式" prop="packagingForm">
                                <a-select @change="packSpecificationChange" v-if="formData.discretion" class="yuan-form-input" v-model="formData.packagingForm" placeholder="请选择包装形式">
                                    <a-select-option value="袋装">袋装</a-select-option>
                                    <a-select-option value="盒装">盒装</a-select-option>
                                </a-select>
                                <span class="yuan-form-placeholder" v-else>请先选择品名</span>
                            </a-form-model-item>

                            <a-form-model-item class="yuan-form-item yuan-form-row-item yuan-form-col3" label="品名"
                                prop="materialCode">
                                <div  v-if="formData.discretion">
                                    <YuanSelectVue show-search class="yuan-form-input" placeholder="请选择" :list="materialList"
                                                   v-model="formData.materialCode" @change="materialChange" val="materialCode" name='varietyName'
                                                   :defName="formData.varietyName" />
                                    <a-button class="primary-empty-btn yuan-form-item-btn" @click="jump('/xls/#/materialMgt')">
                                        档案管理
                                    </a-button>
                                </div>
                                <span class="yuan-form-placeholder" v-else>请先选择包装规格</span>
                            </a-form-model-item>

                            <div class="clear-both"></div>
<!--                            <a-form-model-item class="yuan-form-item" label="存货代码" prop="inventoryCode">-->
<!--                                <span class="yuan-form-show" v-if="formData.materialCode">{{formData.inventoryCode}}</span>-->
<!--                                <span class="yuan-form-placeholder" v-else>请先选择品名</span>-->
<!--                            </a-form-model-item>-->
                            <div class="clear-both"></div>
                            <a-form-model-item class="yuan-form-item yuan-form-col3" label="保质期" prop="expirationDate">
                                <span class="yuan-form-show" v-if="formData.materialCode">{{formData.expirationDate}}月</span>
                                <span class="yuan-form-placeholder" v-else>请先选择品名</span>
                            </a-form-model-item>
<!--                            <a-form-model-item class="yuan-form-item" label="产品大类" prop="productBigKind">-->
<!--                                <span class="yuan-form-show" v-if="formData.materialCode">{{formData.productBigKind}}</span>-->
<!--                                <span class="yuan-form-placeholder" v-else>请先选择品名</span>-->
<!--                            </a-form-model-item>-->
<!--                            <a-form-model-item class="yuan-form-item yuan-form-col3" label="装量" prop="discretion">-->
<!--                                <a-select class="yuan-form-input" v-model="formData.discretion" placeholder="请选择装量"-->
<!--                                          @change="discretionChange" v-if="formData.materialCode">-->
<!--                                    <a-select-option :value="item.value" v-for="(item,idx) in quantityColor"-->
<!--                                                     :key="item.name+'_'+idx">{{item.value}}</a-select-option>-->
<!--                                </a-select>-->
<!--                            </a-form-model-item>-->
<!--                            <a-form-model-item class="yuan-form-item" label="发药机编码" prop="dispensingMachineCoder">-->
<!--                                <span class="yuan-form-show"-->
<!--                                    v-if="formData.materialCode">{{formData.dispensingMachineCoder}}</span>-->
<!--                                <span class="yuan-form-placeholder" v-else>请先选择品名</span>-->
<!--                            </a-form-model-item>-->
                            <a-form-model-item class="yuan-form-item" label="物料代码" prop="materialCode">
                                <span class="yuan-form-show"
                                      v-if="formData.materialCode">{{formData.materialCode}}</span>
                                <span class="yuan-form-placeholder" v-else>请先选择品名</span>
                            </a-form-model-item>
                            <div class="clear-both"></div>
                            <a-form-model-item class="yuan-form-item yuan-form-col3" label="色卡颜色" prop="1">
                                <span class="yuan-form-input"
                                    :style="{'width':'50px',height:'20px','display':'inline-block','background-color':formData.colorChart,'vertical-align':'sub'}"></span>
                            </a-form-model-item>

                            <div class="clear-both"></div>
<!--                            <a-form-model-item class="yuan-form-item" label="规格码" prop="specificationCode">-->
<!--                                <a-input class="yuan-form-input" v-model="formData.specificationCode" placeholder="请输入"></a-input>-->
<!--                            </a-form-model-item>-->
                            <a-form-model-item class="yuan-form-item" label="选择仓库" prop="warehouseId">
                                <YuanSelectVue class="yuan-form-input" placeholder="请选择" :list="warehouseList"
                                    v-model="formData.warehouseId" @change="warehouseChange" val="id" name='name'
                                    :defName="formData.warehouse" />
                            </a-form-model-item>
                            <div class="clear-both"></div>
                            <a-form-model-item class="yuan-form-item yuan-form-col3" label="主批号" prop="advocateBatch">
                                <a-input class="yuan-form-input" v-model="formData.advocateBatch" placeholder="请输入主批号"></a-input>
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-item" label="亚批号" prop="secondBatch">
                                <a-input disabled class="yuan-form-input" v-model="formData.secondBatch" placeholder="请输入亚批号"></a-input>
                            </a-form-model-item>
                            <div class="clear-both"></div>
                            <a-form-model-item class="yuan-form-item" label="产品批号" prop="number">
                                <span class="yuan-form-show" v-if="!formData.advocateBatch">--</span>
                                <span class="yuan-form-show" v-else>{{ formData.advocateBatch }}{{ formData.secondBatch }}</span>
                            </a-form-model-item>
                            <div class="clear-both"></div>
                            <a-form-model-item class="yuan-form-item yuan-form-row-item" label="生产负责人" prop="principalId">
                                <YuanSelectVue show-search class="yuan-form-input" placeholder="请选择" :list="accountList"
                                    v-model="formData.principalId" @change="accountChange" val="userId" name='name'
                                    :defName="formData.principal" />

                                <a-button class="primary-empty-btn yuan-form-item-btn" @click="jump('/xls/#/memberManagement')">
                                    员工管理
                                </a-button>
                            </a-form-model-item>

                            <div class="clear-both"></div>

                            <a-form-model-item class="yuan-form-item" label="生产日期">
                                <a-input class="yuan-form-input" v-model="formData.productionTime" placeholder="请选择投料"
                                    disabled></a-input>
                            </a-form-model-item>
                        </div>
                    </div>
                    <div class="form-panel">
                        <div class="form-panel-title">投料品信息</div>
                        <div class="form-panel-box">
                            <div class="yuan-table">
                                <div class="table-row header-row">
                                    <div class="table-col col-1"></div>
                                    <div class="table-col">名称</div>
                                    <div class="table-col">生产批号</div>
                                    <div class="table-col">投入量</div>
                                    <div class="table-col">质量标准</div>
                                </div>
                                <div class="table-row">
                                    <div class="table-col col-1 mast-ico text-right">投料：</div>
                                    <div class="table-col">
                                        <YuanSelectVue placeholder="请选择" :list="materialListMid" v-model="formData.productionId"
                                            @change="materialListMidChange" :showSearch="true" val="id" name='feedName'
                                            name2='productionBatch' :defName="formData.feedName" />

                                    </div>
                                    <div class="table-col">
                                        <a-input v-model="formData.productionBatch" placeholder="请先选择名称" disabled />

                                    </div>
                                    <div class="table-col">
                                        <a-input :suffix="formData.productionUnit" v-model="formData.putIntoNum"
                                            placeholder="请输入投入量" />

                                    </div>
                                    <div class="table-col">
                                        <a-input v-model="formData.massStandard" placeholder="请选择投料" disabled />
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </a-form-model>
            </a-spin>
            <PackagingDetail :visible="detailVisible" @closeModal="() => detailVisible = false" :infoData="formData"
                :isPreview="true" @submit="submit" />
        </a-modal>
    </div>
</template>

<script lang="ts">
import { Component, Prop, Watch, Vue } from "vue-property-decorator";
import nextApi, { AccountListRes, MaterialListRes, ProductionUsePackRes, ProListRes, WarehouseListRes } from "@/api/nextApi";
import Upload from "@/components/upload.vue";
import PackagingDetail from "./packagingDetail.vue";
import YuanSelectVue from "@/components/yuanSelect.vue";
@Component({
    name: "PackagingAdd",
    components: { Upload, PackagingDetail, YuanSelectVue },
})
export default class extends Vue {
    @Prop({ default: false }) visible!: boolean;
    @Prop({ default: "" }) infoId!: string;
    @Prop({default:''}) rawType!:string;
    @Watch("visible")
    visibleChange() {
        if (this.visible) this.getDetail();
        console.log(this.rawType)
        this.modalOption.title = this.infoId ? "编辑包装" : "新增包装";
    }
    detailVisible = false;
    formLoading = false;
    modalOption = {
        title: "新增包装",
        okText: "预览并提交",
        cancelText: "取消",
        onOk: () => {
            this.modalOk();
        },
        onCancel: () => {
            this.closeModal();
        },
    };
    quantityColor: { value: string; color: string }[] = [];
    rules = {
        materialCode: [{ required: true, message: "请选择物料", trigger: "blur" }],
        medicineClass: [{ required: true, message: "请选择中药等级", trigger: "blur" }],
        warehouseId: [{ required: true, message: "请选择仓库", trigger: "blur" }],
        advocateBatch: [{ required: true, message: "请输入主批号", trigger: "blur" }],
        secondBatch: [{ required: false, message: "请输入亚批号", trigger: "blur" }],
        principalId: [{ required: true, message: "请选择生产负责人", trigger: "blur" }],
    };

    formData: any = {
    };
    tabsData = [
        {name:'中药饮片',rawType:'中药饮片(半成品)'},
        {name:'直服饮片',rawType:'直服饮片(半成品)'},
        {name:'单方饮片',rawType:'单方饮片(半成品)'},
    ]
    resetForm() {
        this.formData = {
        };
    }
    async mounted() {
        this.resetForm();
    }
    closeModal() {
        this.resetForm();
        (this.$refs.form as any).resetFields();
        this.$emit("closeModal");
        this.materialList = []
    }
    modalOk() {
        if (!this.formData.productionId) {
            this.$message.error("请选择投料");
            return;
        }
        if (!this.formData.putIntoNum) {
            this.$message.error("请输入投料量");
            return;
        }
        (this.$refs.form as any).validate(async (valid: any) => {
            if (valid) {
                console.log(this.formData)
                this.formData.productBatch = this.formData.advocateBatch+(this.formData.secondBatch ? this.formData.secondBatch:'')
                this.detailVisible = true;
            }
        });
    }
    async getDetail() {
        this.formLoading = true;
        try {
            await this.getWarehouseList();
            await this.getAccountList();
            if (this.infoId) {
                const res = await nextApi.getPackagingDetail({ id: this.infoId });
                this.formData = { ...res.data };
                const find = this.materialListMid.find((item) => item.id === this.formData.productionId);
                if (find) {
                    this.formData.productionUnit = find.unit;
                }
            } else {
                this.formData = {};
                this.formData.principalId = this.accountList[0].userId
                this.formData.principal = this.accountList[0].name
                let rawType
                if(this.rawType === '中药饮片(半成品)'){
                    rawType = '中药饮片'
                }else if(this.rawType === '直服饮片(半成品)'){
                    rawType = '直服饮片'
                }else{
                    rawType = '单方饮片'
                }
                this.formData.productType = rawType
                await this.getProductVolume();
            }
        } finally {
            this.formLoading = false;
        }
    }
    //中药等级改变
    async medicineClassChange(){
        await this.getProductVolume()
    }
    //查询产品大类
    bigKindList: any[] = [];
    async getProductVolume(){
        const res = await nextApi.getProductVolumeList({productType:this.formData.productType,medicineClass:this.formData.medicineClass})
        this.bigKindList = res.data
        //只保留productBigKind字段并去重
        this.bigKindList = this.bigKindList.map((item)=>item.productBigKind).filter((item,index,self)=>self.indexOf(item)===index)

    }
    materialList: MaterialListRes[] = [];
    materialListMid: ProductionUsePackRes[] = [];
    async getMaterialsMid() {
        const res = await nextApi.getProductionUsePack({
            varietyInitial: this.formData.varietyName,
            productType:this.rawType,

        });
        this.materialListMid = res.data || [];
    }
    warehouseList: WarehouseListRes[] = [];
    async getWarehouseList() {
        if (this.warehouseList && this.warehouseList.length > 0) return;
        const res = await nextApi.getWarehouseList({
            state: 1,
        });
        this.warehouseList = res.data || [];
    }
    accountList: AccountListRes[] = [];
    async getAccountList() {
        if (this.accountList && this.accountList.length > 0) return;
        const res = await nextApi.getAccountList({});
        this.accountList = res.data?.rows || [];
        let curAccount;
        const siteUserInfo = localStorage.getItem('siteUserInfo') ?? '';
        if(siteUserInfo){
            try{
                curAccount = JSON.parse(siteUserInfo)
                let curUserInfo: AccountListRes = {
                    name:curAccount.name,
                    userId:curAccount.id,
                    phone:curAccount.phone,
                    organizationName:curAccount.organizationName
                }
                this.accountList.unshift(curUserInfo)
            }catch (error) {
                console.error('Failed to parse siteUserInfo:', error);
                curAccount = null
            }
        }else{
            curAccount = null
        }
    }

    jump(url: string) {
        window.open(url);
    }
    materialChange() {
        const find = this.materialList.find((item) => item.materialCode === this.formData.materialCode);

        if (find) {
            this.formData.varietyName = find.varietyName;
            this.formData.materialCode = find.materialCode;
            this.formData.varietyAddTime = find.varietyAddTime;
            this.formData.colorChart = find.colorChart;
            this.formData.expirationDate = find.expirationDate;
            this.formData.dispensingMachineCoder = find.dispensingMachineCoder;
            this.formData.medicineValue = find.medicineValue;
            this.formData.productBigKind = find.productBigKind;
            this.getMaterialsMid();
        }
    }
    warehouseChange() {
        const find = this.warehouseList.find((item) => item.id === this.formData.warehouseId);
        if (find) {
            this.formData.warehouse = find.name;
        }
    }
    accountChange() {
        const find = this.accountList.find((item) => item.userId === this.formData.principalId);
        if (find) {
            this.formData.principal = find.name;
        }
    }
    materialListMidChange() {
        const find = this.materialListMid.find((item) => item.id === this.formData.productionId);
        if (find) {
            console.log(find)
            this.formData.feedName = find.feedName;
            this.formData.productionBatch = find.productionBatch;
            this.formData.massStandard = find.massStandard;
            this.formData.productionTime = find.productionTime;
            this.formData.placeOfOrigin = find.placeOfOrigin;
            this.formData.productionUnit = find.unit;
            this.formData.unit = find.unit;
            this.formData.medicineValue = find.medicineValue;
        }
    }
    materialListMidSearch(e: string) {
        this.materialListMid = [];
        this.getMaterialsMid();
    }
    packSpecificationList: any = [];
    async productBigKindChange(){
        const res = await nextApi.getPackSpecificationByKind({kind:this.formData.productBigKind,productType:this.formData.productType})
        this.packSpecificationList = res.data || [];
    }
    async packSpecificationChange(i){
        if(this.formData.productType =='直服饮片' && !this.formData.packagingForm)return
        try {
            let params = {
                kind:this.formData.productBigKind,
                specification:this.formData.discretion,
                productType:this.formData.productType,
                packagingForm:this.formData.packagingForm,
                state:0
            }
            const res = await nextApi.getVarietyNameByBigKindAndSpecification(params)
            if(res.data){
                this.materialList = res.data || [];
            }
        } catch (error) {
            this.materialList = [];
        }
        console.log(this.materialList)
    }
    discretionChange() {
        const find = this.quantityColor.find((item) => item.value === this.formData.discretion);
        if (find) {
            this.formData.colorChart = find.color;
        }
    }

    async submit() {
        this.formLoading = true;
        try {
            const res = await nextApi.editPackaging(this.formData);
            this.$message.success(res.msg);
            this.detailVisible = false;
            this.closeModal();
            this.$emit("resetList");
        } finally {
            this.formLoading = false;
        }
    }
    get confirmMedicineClass(){
        if(this.formData.productType == '中药饮片' && this.formData.medicineClass){
            return true
        }else return this.formData.productType != '中药饮片';
    }
}
</script>
<style lang="scss"></style>
